package com.w1.security.filter;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.w1.security.domain.LoginUser;
import com.w1.security.service.impl.security.JwtDecryptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 跳过登陆
 * @author mingyifan
 * @date 2022-02-16 10:10
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtDecryptService jwtDecryptService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //能拿到登陆用户
        LoginUser loginUser = jwtDecryptService.parseJwt(request);
        if (ObjectUtils.isNotEmpty(loginUser)){
            UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(loginUser, null, new ArrayList<>());
            //存入SecurityContextHolder
            SecurityContextHolder.getContext().setAuthentication(userToken);
        }
        filterChain.doFilter(request,response);
    }
}
